//
//  CLReadViewController.swift
//  CJBookReader
//
//  Created by colin on 2019/3/21.
//  Copyright © 2019 lidi. All rights reserved.
//

import UIKit
import ASValueTrackingSlider

/// 阅读器根页面
class CLReadViewController: CLBaseViewController {
    
    /// 书本信息
    var book = CLBook(chapters: nil)
    
    /// 阅读记录
    var record:CLBookRecord?
    
    /// 阅读菜单UI
    var readMenu:DZMReadMenu!
    
    /// 阅读操作对象
    var readOperation:DZMReadOperation!
    
    private var bookId = 0
    private var targetChapterId:Int?
    
    /// 翻页控制器 (仿真)
    private var pageViewController:UIPageViewController?
    
    /// 翻页控制器 (无效果,覆盖readOperation)
    private var coverController:DZMCoverController?
    
    /// 当前显示的阅读View控制器
    private var currentReadViewController:DZMReadViewController?
    
    /// 用于区分正反面的值(固定)
    private var tempNumber = 1
    
    convenience init(bookId:Int,chapterId:Int?) {
        self.init()
        self.bookId = bookId
        self.targetChapterId = chapterId
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置白色状态栏
        self.isStatusBarLightContent = true
        
        // 初始化控制器操作对象
        self.readOperation = DZMReadOperation(vc: self)
        
        // 初始化阅读UI控制对象
        self.readMenu = DZMReadMenu.readMenu(vc: self, delegate: self)
        
        // 初始化控制器
        self.reloadController(display:self.readOperation.getCurrent(isUpdateFont: true, isSave: true))
                
        //监听是否触发home键挂起程序.
//        NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillResignActive), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
//
//        ///监听是否重新进入程序程序.
//        NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
//        ///监听是否被kill
//        NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillTerminate), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)
        
        self.loadBook()
        
    }
    
    func applicationWillResignActive(){
        print("监听是否触发home键挂起程序.")
        //@colin
        //readMenu.lightView.reSetSystemBrightness()
    }
    
    func applicationDidBecomeActive(){
        print("监听是否重新进入程序程序.")
        //@colin
        //readMenu.lightView.reSetCustomBrightness()
    }
    
    func applicationWillTerminate(){
        print("监听是否进入后台或被kill")
    }
    
    func loadBook() {
        
        self.hud.showProgress()
        
        _ = Router.fetchBookTree(goods_id: self.bookId, token: AccountManager.shared.token).request {[weak self] (response:RequestResponse<[JSONObject]>) in
            
            self?.hud.hide()
            
            if case .success(let resData,_) = response {
                
                let bookData = CLBook(chapters: resData)
                
                self?.book = bookData
                
                // 加载书签
                
                //加载阅读记录
                
                //跳转章节
                if !bookData.chapters.isEmpty {
                    let chapter = self?.book.chapters[0]
                    self?.readOperation.checkChapter(chapterId: chapter!.id, complete: {
                        self?.readOperation.goto(chapter: chapter, page: 0)
                    })
                } else {
                    print("没有章节数据")
                }
            }
            
            if case .failure(_ ,let code) = response {
                print(code)
            }
        }
        
    }
    
    // MARK: -- 创建 PageController
    
    /// 创建效果控制器 传入初始化显示控制器
    func reloadController(display:UIViewController?) {
        
        // 清理
        self.pageViewController?.view.removeFromSuperview()
        self.pageViewController?.removeFromParent()
        self.pageViewController = nil
        
        self.coverController?.view.removeFromSuperview()
        self.coverController?.removeFromParent()
        self.coverController = nil
        
        // 创建
        if CLReadConfigure.shared.effectType == .simulation {
            // 仿真
            let options = [UIPageViewController.OptionsKey.spineLocation:NSNumber(value: UIPageViewController.SpineLocation.min.rawValue as Int)]
            let pageController = UIPageViewController(transitionStyle:.pageCurl,navigationOrientation:.horizontal,options: options)
            pageController.delegate = self
            pageController.dataSource = self
            
            // 为了翻页背面的颜色使用
            pageController.isDoubleSided = true
            
            self.view.insertSubview(pageController.view, at: 0)
            self.addChild(pageController)
            
            var displayControllers:[UIViewController]?
            if let displayController_ = display {
                displayControllers = [displayController_]
            }
            pageController.setViewControllers(displayControllers, direction: .forward, animated: true, completion: nil)
            
            self.pageViewController = pageController
            
        } else {
            // 无效果 覆盖
            let cover = DZMCoverController()
            cover.delegate = self
            self.view.insertSubview(cover.view, at: 0)
            self.addChild(cover)
            cover.setController(display)
            if CLReadConfigure.shared.effectType == .none { cover.openAnimate = false }
            self.coverController = cover
        }
        
        self.readMenu.topView.setTitle(self.record?.chapter?.name)
    
        // 记录
        self.currentReadViewController = display as? DZMReadViewController
    }
    
    deinit {
        // 清理模型
        //self.cjReadModel = nil
    }

}

// MARK: -- DZMReadMenuDelegate
extension CLReadViewController : DZMReadMenuDelegate {
    
    /// 背景颜色
    func readMenuClickSetuptColor(readMenu: DZMReadMenu, index: NSInteger, color: UIColor) {
        CLReadConfigure.shared.colorIndex = index
        //切换到白天模式
        CLReadConfigure.shared.isNight = false
        self.readMenu.bottomView.refreshButtonToggleLight()
        self.currentReadViewController?.configureBGColor()
    }
    
    /// 翻书动画
    func readMenuClickSetuptEffect(readMenu: DZMReadMenu, index: NSInteger) {
        CLReadConfigure.shared.effectType = CLEffectType(index: index)
        self.reloadController(display:self.readOperation.getCurrent())
    }
    
    /// 字体
    func readMenuClickSetuptFont(readMenu: DZMReadMenu, index: NSInteger) {
        CLReadConfigure.shared.fontType = CLFontType(index: index)
        self.reloadController(display:self.readOperation.getCurrent(isUpdateFont: true, isSave: true))
    }
    
    /// 字体大小
    func readMenuClickSetuptFontSize(readMenu: DZMReadMenu, fontSize: CGFloat) {
        // CLReadConfigure.shared.fontSize = fontSize 内部已赋值
        self.reloadController(display:self.readOperation.getCurrent(isUpdateFont: true, isSave: true))
    }
    
    /// 点击返回按钮
    func readMenuClickBackButton(readMenu: DZMReadMenu, button: UIButton) {
        print("点击返回按钮-------")
        
        //@colin
        //self.readMenu.lightView.reSetSystemBrightness()
        
        let _ = self.navigationController?.popViewController(animated: true)
        self.dismiss(animated: true, completion: nil)
        
        UIApplication.shared.setStatusBarHidden(false, with: .fade)
        UIApplication.shared.setStatusBarStyle(.default, animated: true)
        
    }
    
    /// 下载
    func readMenuClickDownload(readMenu: DZMReadMenu) {
        
        print("点击了下载")
    }
    
    /// 拖拽进度条
    func readMenuSliderEndScroll(readMenu: DZMReadMenu, slider: ASValueTrackingSlider) {
        let toPage = Int(slider.value) - 1
        if self.record?.page != toPage {
            self.record?.page = toPage
            let page = self.readOperation.getCurrent(isUpdateFont: true,isSave: true)
            self.reloadController(display:page)
        }
    }
    
    /// 上一章
    func readMenuClickPreviousChapter(readMenu: DZMReadMenu) {
        if let index = self.book.chapters.firstIndex(where: { (item) -> Bool in
            return item.id == self.record?.chapter?.id
        }) {
            let preIndex = index - 1
            if preIndex >= 0 {
                let chapter = self.book.chapters[preIndex]
                self.readOperation.checkChapter(chapterId: chapter.id) { [weak self] in
                    self?.readOperation.goto(chapter: chapter, page: 0)
                }
            }
        } else {
            print("未找到章节")
        }
    }
    
    /// 下一章
    func readMenuClickNextChapter(readMenu: DZMReadMenu) {
        if let index = self.book.chapters.firstIndex(where: { (item) -> Bool in
            return item.id == self.record?.chapter?.id
        }) {
            let nextIndex = index + 1
            if nextIndex < self.book.chapters.count {
                let chapter = self.book.chapters[nextIndex]
                self.readOperation.checkChapter(chapterId: chapter.id) { [weak self] in
                    self?.readOperation.goto(chapter: chapter, page: 0)
                }
            }
        } else {
            print("未找到章节")
        }
    }
    
    /// 点击章节列表
    func readMenuClickChapterList(readMenu: DZMReadMenu, index: Int) {
        let chapter = self.book.chapters[index]
        // 先检查章节是否存在，是否需要购买
        self.readOperation.checkChapter(chapterId: chapter.id) { [weak self] in
            self?.readOperation.goto(chapter: chapter, page: 0)
        }
    }
    
    /// 切换日夜间模式
    func readMenuClickLightButton(readMenu: DZMReadMenu, isDay: Bool) {
        
        if isDay {
            self.currentReadViewController?.configureNightBGColor()
            self.currentReadViewController?.tableView.reloadData()
        }else{
            self.currentReadViewController?.configureBGColor()
            self.currentReadViewController?.tableView.reloadData()
            
        }
    }
    
    /// 状态栏 将要 - 隐藏以及显示状态改变
    func readMenuWillShowOrHidden(readMenu: DZMReadMenu, isShow: Bool) {
        self.pageViewController?.tapGestureRecognizerEnabled = !isShow
        self.coverController?.tapGestureRecognizerEnabled = !isShow
    }
    
    /// 点击更多按钮
    func readMenuClickMoreButton(readMenu: DZMReadMenu, button: UIButton) {
        
        //let hasMark = self.cjReadModel.isMarkExist(readRecord: self.cjReadModel.record)
        //let hasReward = self.cjReadModel.bookType == .txt
        
        /*
        CJMorePopverView(frame: CGRect.zero).show(hasMark: hasMark, hasReward: hasReward, searchHandle: {
            //检索
            
        }, markHandle: {
            
            if hasMark {
                //移除书签
                self.cjReadModel.deleteReadmark(readMark: nil, index: nil, callback:nil)
            } else {
                //添加书签
                var chapter_id = ""
                var content = ""
                var book_type = ""
                var chapter_name = ""
                var book_id = ""
                if self.cjReadModel.bookType == .txt {
                    book_type = "1"
                    book_id = self.cjReadModel.txtBookInfo.book_id
                    if let txt = self.cjReadModel.record.txtChapter {
                        chapter_id = txt.ch_id
                        let range = txt.pageRanges[self.cjReadModel.record.page]
                        content = txt.content.substring(range)
                        chapter_name = txt.ch_name
                    }
                } else {
                    book_type = "2"
                    book_id = self.cjReadModel.epubBookInfo.book_id
                    if let epub = self.cjReadModel.record.epubChapter {
                        chapter_id = epub.id
                        content = epub.contentFor(page: self.cjReadModel.record.page)
                        chapter_name = epub.name
                    }
                }
                
                if !chapter_id.isEmpty {
                    
                    MBProgressHUD.showMessage(to: self.view)
                    
                    _ = Router._addBookMark(chapter_id: chapter_id, content: content, book_type: book_type,chapter_name: chapter_name,book_id: book_id).request({[weak self] (response:YLLResponse<JSONObject>) in
                        
                        MBProgressHUD.hideAllHUDs(for: self?.view, animated: true)
                        
                        if case .success(let res,_) = response {
                            if let weakSelf = self {
                                var markId = ""
                                if let markId_ = res?["mark_id"] as? Int {
                                    markId = String(markId_)
                                }
                                
                                if let markId_ = res?["mark_id"] as? String {
                                    markId = markId_
                                }
                                
                                if !markId.isEmpty {
                                    weakSelf.cjReadModel.addRemark(readRecord: weakSelf.cjReadModel.record,markId: markId)
                                }
                            }
                        }
                        
                        if case .failure(let message,let code) = response {
                            if code == 600 {
                                self?.readMenu.jumpLogin()
                            } else {
                                MBProgressHUD.showError(message, to: self?.view)
                            }
                        }
                    })
                }
            }
            
        }, shareHandle: {
            //分享
            
        }, rewardHandle: { [weak self] in
            // self?.reward()
        })
        */
    }
    
}

// MARK: -- DZMCoverControllerDelegate
extension CLReadViewController : DZMCoverControllerDelegate {
    
    /// 切换结果
    public func coverController(_ coverController: DZMCoverController, currentController: UIViewController?, finish isFinish: Bool) {
        // 记录
        self.currentReadViewController = currentController as? DZMReadViewController
        // 更新阅读记录
        self.readOperation.update(record: self.currentReadViewController?.chapterPage)
    }
    
    /// 将要显示的控制器
    public func coverController(_ coverController: DZMCoverController, willTransitionToPendingController pendingController: UIViewController?) {
        self.readMenu.menuSH(isShow: false)
    }
    
    /// 获取上一个控制器
    public func coverController(_ coverController: DZMCoverController, getAboveControllerWithCurrentController currentController: UIViewController?) -> UIViewController? {
        return self.readOperation.getAbove()
    }
    
    /// 获取下一个控制器
    public func coverController(_ coverController: DZMCoverController, getBelowControllerWithCurrentController currentController: UIViewController?) -> UIViewController? {
        return self.readOperation.getBelow()
    }
    
}

// MARK: -- UIPageViewControllerDataSource
extension CLReadViewController : UIPageViewControllerDataSource {
    
    /// 获取上一页
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        
        self.tempNumber -= 1
        
        if abs(self.tempNumber) % 2 == 0 { // 背面
            
            let vc = UIViewController()
            // 配置背景颜色
            
            if CLReadConfigure.shared.isNight {
                vc.view.backgroundColor = UIColor.readHeaderAndFooterText.night
            }else{
                vc.view.backgroundColor =  CLReadConfigure.shared.readColor
            }
            return vc
            
        } else { // 内容
            return readOperation.getAbove()
        }
    }
    
    /// 获取下一页
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        
        self.tempNumber += 1
        
        if abs(self.tempNumber) % 2 == 0 { // 背面
            
            let vc = UIViewController()
            
            // 配置背景颜色
            if CLReadConfigure.shared.isNight {
                vc.view.backgroundColor =  UIColor.readHeaderAndFooterText.night
            }else{
                vc.view.backgroundColor =  CLReadConfigure.shared.readColor
            }
            return vc
            
        } else { // 内容
            return self.readOperation.getBelow()
        }
    }
}

// MARK: -- UIPageViewControllerDelegate
extension CLReadViewController : UIPageViewControllerDelegate {
    
    /// 切换结果
    public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        
        if !completed {
            // 记录
            self.currentReadViewController = previousViewControllers.first as? DZMReadViewController
        } else {
            // 记录
            self.currentReadViewController = pageViewController.viewControllers?.first as? DZMReadViewController
        }
        
        // 更新阅读记录
        self.readOperation.update(record: self.currentReadViewController?.chapterPage)
    }
    
    /// 准备切换
    public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        
        // 隐藏菜单
        self.readMenu.menuSH(isShow: false)
        
        // 更新阅读记录
        let controller = pageViewController.viewControllers?.first as? DZMReadViewController
        self.readOperation.update(record: controller?.chapterPage, isSave: false)
    }
    
}
